const {saveAs} = require("./FileSaver")
const JSZip = require("./jszip.min")
function JszipTool(){
    this.saveArr = [];
}
JszipTool.prototype.add = function(data){
    this.saveArr.push(data);
}
JszipTool.prototype.clear = function(){
    this.saveArr = [];
}
JszipTool.prototype.saveFile = function(name,type="png",imgData){
    let dataURL = imgData.replace("image/png", "image/octet-stream");
    var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    save_link.href = dataURL;
    save_link.download = name +"." + type;
    var event = document.createEvent('MouseEvents');
    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    save_link.dispatchEvent(event);
}
JszipTool.prototype.saveCanvasPngToFile = function(name,canvas,type,callback){
    return new Promise((resolve)=>{
        canvas.toBlob((blob)=>{
            saveAs(blob, name + ".png");
            callback && callback()
        })
    })
}
JszipTool.prototype.saveFileArr = function(name,arr,callback){
    if(!arr.unshift){
        callback = arr;
        arr = this.saveArr;
    }
    var zip = new JSZip();
    for(let i = 0;i<arr.length;i++){
        let item = arr[i]
        let imgData = item.data;
        // imgData = imgData.replace(/^data:image\/\w+;base64,/, "");
        zip.file(item.name+"."+"png", imgData);
    }
    zip.generateAsync({type:"blob"})
    .then(function(content) {
        saveAs(content, name + ".zip");
        callback(name + ".zip")
    });
}
module.exports = JszipTool;